import { Collection, DatasetListItem } from '@/common';
import BreadCrumb from '../BreadCrumb';
import { useEffect, useState } from 'react';
import { ItemType } from 'antd/es/breadcrumb/Breadcrumb';
import ApiListTableMain from '../RoleListTableMain';
import { Role } from '@/types/role';
import { useRoleManage, useRoles } from '@/store/roleManageStore';
import { findNodeById } from '@/utils/tree';
import { Skeleton, Space } from 'antd';

interface Props {
  loading: boolean;
  onItemClicked?: (item: Role | undefined) => void;
  isAdmin: boolean;
  isPermit: boolean;
  version?: string;
}

const RoleDetail = ({ loading, isAdmin, isPermit, onItemClicked, version }: Props) => {
  const [crumbs, setCrumbs] = useState<ItemType[]>([]);
  const roleManage = useRoleManage();
  const roles = useRoles();
  const findParentArray = (roles: Role[], id: string) => {
    const search = (role: Role, items: ItemType[]): ItemType[] | null => {
      if (role.id == id) {
        return items;
      }

      if (role.children) {
        for (const child of role.children) {
          const result = search(child, [...items, { key: role.id, title: role.name }]);
          if (result) {
            return result;
          }
        }
      }
      return null;
    };
    for (const role of roles) {
      const result = search(role, []);
      if (result) {
        return result;
      }
    }
    return null;
  };

  const onBreadCrumbClicked = (item: ItemType | undefined) => {
    if (item) {
      const role = findNodeById(roles, item.key?.toString() ?? '');
      onItemClicked && onItemClicked(role);
    } else {
      onItemClicked && onItemClicked(undefined);
    }
  };

  useEffect(() => {
    if (roleManage.selectedRole) {
      const array = findParentArray(roles, roleManage.selectedRole.id);
      setCrumbs(
        array
          ? [...array, { key: roleManage.selectedRole.id, title: roleManage.selectedRole.name }]
          : [],
      );
    } else {
      setCrumbs([]);
    }
  }, [roleManage.selectedRole, roles]);

  return (
    <>
      {loading && (
        <div>
          <Space>
            <Skeleton.Input active size={'small'} />
            {/* <Skeleton.Button active={active} size={size} shape={buttonShape} block={block} /> */}
          </Space>
          <br />
          <br />
          <br />
          <Skeleton active paragraph={{ rows: 24 }} />
        </div>
      )}
      {!loading && (
        <div className="flex h-full w-full flex-col">
          <BreadCrumb disable={false} crumbs={crumbs} onItemClicked={onBreadCrumbClicked} />
          <ApiListTableMain
            datas={roles}
            isAdmin={isAdmin}
            isPermit={isPermit}
            selectedItem={roleManage.selectedRole}
            onItemClicked={onItemClicked}
            version={version}
          />
        </div>
      )}
    </>
  );
};

export default RoleDetail;
